<!--
  -    Copyright (c) 2018-2025, lengleng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: lengleng (wangiegie@gmail.com)
  -->
  <template>
    <!-- 巡检单 -->
    <div class="layout-padding">
      <basic-container class="layout-padding-auto layout-padding-view">
        <avue-crud
            ref="crud"
            v-model="form"
            :before-open="handleOpenBefore"
            :page="page"
            :data="tableData"
            :permission="permissionList"
            :table-loading="tableLoading"
            :option="tableOption"
            :cell-class-name="addClass"
            @row-click="handleRowClick"
            @on-load="getList"
            @search-change="searchChange"
            @refresh-change="refreshChange"
            @size-change="sizeChange"
            @current-change="currentChange"
            @row-update="handleUpdate"
            @row-save="handleSave"
            @selection-change="selectionChange"
        >
          <!-- <template #checkDeptId-form="{ row }">
            <avue-input-tree
              v-model="form.checkDeptId"
              :dic="treeLocationData"
              :props="defaultPropstree"
              type="tree"
              placeholder="请选择巡检部门"
            ></avue-input-tree>
          </template> -->
          <template #menu="scope">
            <!-- v-if="permissions.sys_user_edit" -->
            <el-button
               
                text
                type="primary"
                :disabled='scope.row.sheetStatus=="3"||scope.row.sheetStatus=="4"'
                icon="el-icon-edit"
                @click="ClickUpdateBtn(scope.row, scope.index)"
            >编辑
            </el-button>
            <!-- v-if="permissions.om_omichecksheet_del" -->
             <el-button
                 
                 text
                 type="primary"
                 icon="el-icon-delete"
                 @click="rowDel(scope.row)"
             >删除
            </el-button>
          </template>
          <template #menu-left>
            <el-button
                class="filter-item"
                plain
                type="primary"
                icon="el-icon-delete"
                @click="plDelete"
            >
              批量删除
            </el-button>
          </template>
          <template #sheetStatus="{ row }">
            <el-tag v-if="row.sheetStatus == '1'">待申领</el-tag>
            <el-tag v-if="row.sheetStatus == '2'">未开始</el-tag>
            <el-tag type="warning" v-if="row.sheetStatus == '3'">执行中</el-tag>
            <el-tag type="success" v-if="row.sheetStatus == '4'">已结束</el-tag>
            <el-tag type="warning" v-if="row.sheetStatus == '5'">已逾期</el-tag>
          </template>
  
          <template #routeMoudle-form>
            <el-radio v-model="form.routeMoudle" label="1" border>临时巡检</el-radio>
          </template>
          <template #planNo-form>
            <avue-select
                v-model="form.planNo"
                :disabled="form.routeMoudle === '1'"
                :dic="planeData"
                :props="defaultProps"
                placeholder="请选择巡检计划"
            >
            </avue-select>
          </template>
          <template #excuteStartTime-form>
            <el-time-select
                placeholder="开始时间"
                v-model="form.excuteStartTime"
                start="00:00"
                step="00:30"
                end="23:59"
            >
            </el-time-select
            ></template>
          <template #excuteEndTime-form>
            <el-time-select
                placeholder="结束时间"
                v-model="form.excuteEndTime"
                start="00:00"
                step="00:30"
                end="23:59"
                :minTime="form.excuteStartTime"
            >
            </el-time-select
            ></template>
        </avue-crud>
      </basic-container>
      <CheckSheetInfo ref="checkSheetInfo"></CheckSheetInfo>
    </div>
  </template>
  
  <script>
  import {
    fetchList,
    getObj,
    addObj,
    putObj,
    delObj,
    fetchTree,
    userList,
    getCheckPlan,
    getCheckInfo,
    delAllObj
  } from '/@/api/check/omichecksheet'
  import {getUserById} from '/@/api/om/omworder'
  import {tableOption} from '/@/const/crud/check/omichecksheet'
//   import {mapGetters} from 'vuex'
  // import CheckSheetInfo from '/@/views/omcheck/omichecksheet/info/index.vue'
  import CheckSheetInfo from '/@/views/omcheck/configuration/omichecksheet/info/index.vue'
  
  export default {
    components: {CheckSheetInfo},
    name: 'omichecksheet',
    data() {
      return {
        defaultPropstree: {
          label: 'name',
          value: 'id'
        },
        treeLocationData: [],
        form: {},
        searchForm: {},
        tableData: [],
        planeData: [],
        handlerUserData: [],
        defaultProps: {
          label: 'planName',
          value: 'planNo'
        },
        excuteStartTime: '',
        excuteEndTime: '',
        userData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        selectList: []
      }
    },
    computed: {
    //   ...mapGetters(['permissions']),
      permissionList() {
        return {
        //   addBtn: this.validData(this.permissions.om_omichecksheet_add, false),
        //   delBtn: this.validData(this.permissions.om_omichecksheet_del, false),
        //   editBtn: this.validData(this.permissions.om_omichecksheet_edit, false)
        }
      }
    },
    watch: {
      'form.checkUserId': {
        handler(val, oldVal) {
          if (val) {
            userList({current:1,size: 9999}).then((res) => {
              this.userData = res.data
              this.form.checkUserPhone = this.userData.phone
              this.form.checkUserName = this.userData.name
            })
          }
        }
      },
      'form.planNo': {
        handler(val, oldVal) {
          if (val) {
            let list = this.planeData.find((item) => item.planNo === val)
            if (list) {
              this.form.routeId = list.routeId
              this.form.checkDeptId = list.checkDeptId
              this.form.checkUserId = list.checkUserId
              this.form.checkUserPhone = list.checkUserPhone
            }
          }
        }
      }
  
      // 'form.routeMoudle': {
      //   handler(val) {
      //     let planNo = this.findObject(this.tableOption.column, 'planNo')
      //     if (val === '1') {
      //       planNo.disabled = true
      //     } else {
      //       planNo.disabled = false
      //     }
      //   }
      // }
    },
    mounted() {
    },
    methods: {
      ClickUpdateBtn(row, index) {
        this.$refs.crud.rowEdit(row, index)
      },
      selectionChange(list) {
        this.selectList = list
      },
      handleLocation() {
        fetchTree().then((response) => {
          this.treeLocationData = response.data.data
        })
      },
      handleOpenBefore(show, type) {
        this.form.routeMoudle = '1'
        if (type === 'edit') {
          let arr = []
          this.form.userRelList.forEach((item) => {
            let num = item.checkUserId
            arr.push(num)
          })
          this.form.userRelList = arr
  
          this.$refs.checkSheetInfo.activeNames = null
        }
        getCheckPlan().then((res) => {
          this.planeData = res.data
        })
        show()
      },
      getList(page, params) {
        this.tableLoading = true
        fetchList(
            Object.assign(
                {
                  current: page.currentPage,
                  size: page.pageSize
                },
                params,
                this.searchForm
            )
        )
            .then((response) => {
              this.tableData = response.data.records
              this.page.total = response.data.total
              this.tableLoading = false
            })
            .catch(() => {
              this.tableLoading = false
            })
      },
      rowDel: function (row, index) {
        this.$confirm('是否确认删除' + row.checkName, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
            .then(function () {
              return delObj(row.stId)
            })
            .then((data) => {
              this.$message.success('删除成功')
              this.getList(this.page)
            })
            .catch((cancelorerror) => {
            })
      },
      handleUpdate: function (row, index, done, loading) {
        let arr = row.userRelList
        let obj = {}
        // // 将数组转化为对象
        for (let key in arr) {
          obj[key] = arr[key]
        }
        row.userRelList = Object.keys(obj).map((val) => ({
          checkUserId: obj[val]
        }))
        putObj(row)
            .then((data) => {
              this.$message.success('修改成功')
              done()
              this.getList(this.page)
            })
            .catch(() => {
              loading()
            })
      },
      handleSave: function (row, done, loading) {
        let arr = row.userRelList
        let obj = {}
        // // 将数组转化为对象
        for (let key in arr) {
          obj[key] = arr[key]
        }
        row.userRelList = Object.keys(obj).map((val) => ({
          checkUserId: obj[val]
        }))
        addObj(row)
            .then((data) => {
              this.$message.success('添加成功')
              done()
              this.getList(this.page)
            })
            .catch(() => {
              loading()
            })
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      currentChange(current) {
        this.page.currentPage = current
      },
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      refreshChange() {
        this.getList(this.page)
      },
      addClass({row, column, rowIndex, columnIndex}) {
        if (columnIndex === 2) {
          return 'cell-blue'
        }
      },
      handleRowClick(row, column, e) {
        if (column?.property === 'menu') return false
        this.$refs.checkSheetInfo.dialogVisible = true
        getCheckInfo({stId: row.stId}).then((res) => {
          let list = res.data
          if (list.checkUserId === null) {
            this.$refs.checkSheetInfo.infoData = list
          } else {
            // getUserById(list.checkUserId).then((res) => {
              userList(list.checkUserId).then((res) => {
              list.checkUserPhone = res.data?.phone
              this.$refs.checkSheetInfo.infoData = list
            })
          }
        })
      },
      //批量删除
      plDelete() {
        if (this.selectList.length > 0) {
          this.$confirm('是否确认删除以选择的数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
              .then(() => {
                let ids = []
                this.selectList.forEach((data) => {
                  ids.push(data.stId)
                })
                return delAllObj(ids)
              })
              .then((data) => {
                this.$message.success('删除成功')
                this.getList(this.page)
              })
              .catch((cancelorerror) => {
              })
        }
      }
    }
  }
  </script>
  <style lang="scss" scoped>
  ::v-deep .el-table__row {
    cursor: pointer !important;
  }
  </style>
  <style>
  .cell-blue {
    color: #409eff !important;
  }
  </style>
  